import os
from django.conf import settings
from django.db.models import Avg, Sum, Count, Max, Min, Q, F
from django.forms.models import model_to_dict

from rest_framework import serializers
from rest_framework import fields
from rest_framework.serializers import *
from rest_framework.validators import UniqueValidator, UniqueTogetherValidator  # 验证器

# from allinpay import apidev as PAY
from iClouds.apidev import py_str
from mysqldb.models import *
from mysqldb import redis as REDIS
from mysqldb.serializers import ListDjangoFilterBackend

from datetime import datetime, date

# 处理场所自增
# sess, faq = AllinpayPlaceList.objects.update_or_create(
#     defaults={"telephone": "13000000000", "name": "ceshiplace"}, id=1000
# )


def installRoleConf(pid):
    """初始化角色配置"""
    data = [
        AllinpayPlaceroleList(pid=pid, name="实习员工"),
        AllinpayPlaceroleList(pid=pid, name="管理员"),
    ]
    AllinpayPlaceroleList.objects.bulk_create(data)


def installRolePermConf(rid, vid):
    """初始化管理员角色权限-场所"""
    data = [AllinpayPlacerolePerm(rid=rid, vid=i) for i in vid]
    AllinpayPlacerolePerm.objects.bulk_create(data)


def installRolePermYunConf(rid, vid):
    """初始化管理员角色权限-云端"""
    data = [AllinpayPlacerolePermYun(rid=rid, vid=i) for i in vid]
    AllinpayPlacerolePermYun.objects.bulk_create(data)


def installMemberConf(pid):
    """初始化会员配置"""
    data = [
        AllinpayMemberConf(name="birthday", pid=pid, status=0, remarks="生日祝福发送邮件"),
        AllinpayMemberConf(name="activity", pid=pid, status=0, remarks="活动推广发送邮件"),
    ]
    AllinpayMemberConf.objects.bulk_create(data)

    data = [
        MemberLevelruleList(
            **{"status": 1, "lastreg": 7, "bem": "刚注册7天", "pid": pid, "name": "新会员"}
        ),
        MemberLevelruleList(
            **{"status": 1, "lastreg": 30, "bem": "刚注册30天", "pid": pid, "name": "不稳定会员"}
        ),
        MemberLevelruleList(
            **{"status": 1, "week": 3, "bem": "一周到店3次"}, pid=pid, name="常来会员"
        ),
        MemberLevelruleList(
            **{"status": 1, "week": 5, "bem": "一周到店5次"}, pid=pid, name="忠实会员"
        ),
        MemberLevelruleList(
            **{
                "status": 1,
                "lol": 200,
                "csgo": 20000,
                "steam": 20000,
                "bem": "lol指数达到200，Steam指数达到20000，csgo指数达到20000",
            },
            pid=pid,
            name="潜在大咖",
        ),
        MemberLevelruleList(
            **{"status": 1, "other": 100, "bem": "综合排名前100"}, pid=pid, name="大咖100"
        ),
    ]
    MemberLevelruleList.objects.bulk_create(data)


def installBankConf(pid):
    """初始化场所经营账户"""
    data = [
        AllinpayPlacebankList(pid=pid, money=0, status=1, currentime=timezone.now())
    ]
    AllinpayPlacebankList.objects.bulk_create(data)


def installCallmeConf(pid):
    """初始化呼叫配置"""
    data = [
        AllinpayCallmeConf(
            name="直接呼叫",
            pid=pid,
            status=1,
            remarks="0 前台应答,1 随机派单,2 轮流派单,3 抢单模式,4 固定指派",
            timeout=180,
            reward=0,
            redemption=0,
            dispatch=1,
            le0=0,
            le1=0,
            le2=0,
            le3=0,
            le4=0,
            le5=0,
            appurl="LoginBefor/callOrder/callOrder",
        ),
        AllinpayCallmeConf(
            name="专人呼叫",
            pid=pid,
            status=1,
            timeout=180,
            reward=0,
            redemption=0,
            dispatch=4,
            remarks="0 前台应答,1 随机派单,2 轮流派单,3 抢单模式,4 固定指派",
            le0=0,
            le1=0,
            le2=0,
            le3=0,
            le4=0,
            le5=0,
            appurl="LoginBefor/callOrder/callOrder",
        ),
        AllinpayCallmeConf(
            name="专属呼叫",
            pid=pid,
            status=1,
            timeout=180,
            reward=0,
            redemption=0,
            dispatch=1,
            remarks="0 前台应答,1 随机派单,2 轮流派单,3 抢单模式,4 固定指派",
            le0=0,
            le1=0,
            le2=0,
            le3=0,
            le4=0,
            le5=0,
            appurl="LoginBefor/callOrder/callOrder",
        ),
        AllinpayCallmeConf(
            name="配送服务",
            pid=pid,
            status=1,
            timeout=600,
            reward=0,
            redemption=0,
            dispatch=1,
            remarks="0 前台应答,1 随机派单,2 轮流派单,3 抢单模式,4 固定指派",
            le0=0,
            le1=0,
            le2=0,
            le3=0,
            le4=0,
            le5=0,
            appurl="/LoginBefor/saleOrder/saleOrder",
        ),
        AllinpayCallmeConf(
            name="清扫服务",
            pid=pid,
            status=1,
            timeout=600,
            reward=0,
            redemption=0,
            dispatch=1,
            remarks="0 前台应答,1 随机派单,2 轮流派单,3 抢单模式,4 固定指派",
            le0=0,
            le1=0,
            le2=0,
            le3=0,
            le4=0,
            le5=0,
            appurl="/LoginBefor/hardwareOrder/hardwareOrder",
        ),
    ]
    AllinpayCallmeConf.objects.bulk_create(data)


def installHardWareConf(pid):
    """初始化资产配置"""
    data = [
        AllinpayHardwareConf(
            **{
                "name": "area",
                "compare": "equal",
                "value": "1",
                "pid": pid,
                "status": 0,
                "remarks": "区域变更预警",
            }
        ),
        AllinpayHardwareConf(
            **{
                "name": "ipaddr",
                "compare": "equal",
                "value": "1",
                "pid": pid,
                "status": 0,
                "remarks": "IP变更预警",
            }
        ),
        AllinpayHardwareConf(
            **{
                "name": "mac",
                "compare": "equal",
                "value": "1",
                "pid": pid,
                "status": 0,
                "remarks": "MAC变更预警",
            }
        ),
        AllinpayHardwareConf(
            **{
                "name": "board",
                "compare": "equal",
                "value": "1",
                "pid": pid,
                "status": 0,
                "remarks": "主板变更预警",
            }
        ),
        AllinpayHardwareConf(
            **{
                "name": "cpu",
                "compare": "equal",
                "value": "1",
                "pid": pid,
                "status": 0,
                "remarks": "CPU变更预警",
            }
        ),
        AllinpayHardwareConf(
            **{
                "name": "memory",
                "compare": "equal",
                "value": "1",
                "pid": pid,
                "status": 0,
                "remarks": "内存变更预警",
            }
        ),
        AllinpayHardwareConf(
            **{
                "name": "video",
                "compare": "equal",
                "value": "1",
                "pid": pid,
                "status": 0,
                "remarks": "显卡变更预警",
            }
        ),
        AllinpayHardwareConf(
            **{
                "name": "display",
                "compare": "equal",
                "value": "1",
                "pid": pid,
                "status": 0,
                "remarks": "显示器变更预警",
            }
        ),
        AllinpayHardwareConf(
            **{
                "name": "netadapter",
                "compare": "equal",
                "value": "1",
                "pid": pid,
                "status": 0,
                "remarks": "网卡变更预警",
            }
        ),
        AllinpayHardwareConf(
            **{
                "name": "network",
                "compare": "equal",
                "value": "1",
                "pid": pid,
                "status": 0,
                "remarks": "网络连接变更预警",
            }
        ),
        AllinpayHardwareConf(
            **{
                "name": "mouse",
                "compare": "equal",
                "value": "1",
                "pid": pid,
                "status": 0,
                "remarks": "鼠标变更预警",
            }
        ),
        AllinpayHardwareConf(
            **{
                "name": "keyboard",
                "compare": "equal",
                "value": "1",
                "pid": pid,
                "status": 0,
                "remarks": "键盘变更预警",
            }
        ),
        AllinpayHardwareConf(
            **{
                "name": "headset",
                "compare": "equal",
                "value": "1",
                "pid": pid,
                "status": 0,
                "remarks": "音频设备变更预警",
            }
        ),
        AllinpayHardwareConf(
            **{
                "name": "cpu_temperature",
                "compare": "gt",
                "value": "90",
                "pid": pid,
                "status": 0,
                "remarks": "CPU温度阈值报警",
            }
        ),
        AllinpayHardwareConf(
            **{
                "name": "board_temperature",
                "compare": "gt",
                "value": "90",
                "pid": pid,
                "status": 0,
                "remarks": "主板温度阈值报警",
            }
        ),
        AllinpayHardwareConf(
            **{
                "name": "video_temperature",
                "compare": "gt",
                "value": "90",
                "pid": pid,
                "status": 0,
                "remarks": "显卡温度阈值报警",
            }
        ),
        AllinpayHardwareConf(
            **{
                "name": "speed",
                "compare": "lt",
                "value": "1000",
                "pid": pid,
                "status": 0,
                "remarks": "网卡速率阈值报警",
            }
        ),
    ]
    AllinpayHardwareConf.objects.bulk_create(data)


class NoneSerializer(serializers.Serializer):
    """无序列化"""

    class Meta:
        fields = "__all__"


class AllinpayPlaceListSerializer(serializers.ModelSerializer):
    """创建场所"""

    name = CharField(
        max_length=255,
        required=True,
        help_text="门店全称",
        validators=[UniqueValidator(queryset=AllinpayPlaceList.objects.all())],
    )
    telephone = CharField(
        max_length=255,
        required=True,
        help_text="联系电话(必填)",
    )
    basename = CharField(default="", required=False, help_text="门店简称")
    status = HiddenField(default=0)
    fee = HiddenField(default=0)
    creattime = HiddenField(default=timezone.now)

    class Meta:
        model = AllinpayPlaceList
        fields = ("name", "basename", "telephone", "status", "fee", "creattime")
        # fields = "__all__"


class AllinpayPlaceInfoSerializer(serializers.ModelSerializer):
    """创建场所"""

    id = IntegerField(label="ID", read_only=True)
    basename = CharField(
        max_length=255,
        required=False,
        help_text="门店简称",
    )
    name = CharField(
        max_length=255,
        required=False,
        help_text="门店全称",
        validators=[UniqueValidator(queryset=AllinpayPlaceList.objects.all())],
    )
    telephone = CharField(
        max_length=255,
        required=True,
        help_text="超级管理员(必填,手机号码)",
    )
    phone = CharField(
        max_length=255,
        required=False,
        help_text="场所联系电话",
    )
    shopcode = CharField(
        max_length=255,
        required=False,
        help_text="社会统一代码",
        validators=[UniqueValidator(queryset=AllinpayPlaceList.objects.all())],
    )
    licens = CharField(
        max_length=255,
        required=False,
        help_text="上传营业执照",
        validators=[UniqueValidator(queryset=AllinpayPlaceList.objects.all())],
    )
    person = CharField(
        max_length=255,
        required=False,
        help_text="企业法人",
    )
    percode = RegexField(
        r"^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$",
        required=False,
        help_text="法人身份证号码",
    )
    codea = CharField(
        max_length=255,
        required=False,
        help_text="法人身份证正面",
        validators=[UniqueValidator(queryset=AllinpayPlaceList.objects.all())],
    )
    codeb = CharField(
        max_length=255,
        required=False,
        help_text="法人身份证背面",
        validators=[UniqueValidator(queryset=AllinpayPlaceList.objects.all())],
    )
    titles = CharField(
        max_length=255,
        required=False,
        help_text="经营场所照片",
        validators=[UniqueValidator(queryset=AllinpayPlaceList.objects.all())],
    )
    sheng = CharField(
        max_length=255,
        required=False,
        help_text="省",
    )
    shi = CharField(
        max_length=255,
        required=False,
        help_text="市",
    )
    xian = CharField(
        max_length=255,
        required=False,
        help_text="县/区",
    )
    addre = CharField(
        max_length=255,
        required=False,
        help_text="详细地址",
    )
    auth = IntegerField(min_value=0, default=0, help_text="连锁ID")
    creattime = ReadOnlyField()
    status = ReadOnlyField()
    fee = ReadOnlyField()

    barcode = CharField(
        max_length=255,
        required=False,
        help_text="场所编码",
    )

    addr = ReadOnlyField()
    version = SerializerMethodField()

    class Meta:
        model = AllinpayPlaceList
        fields = "__all__"

    def get_version(self, attr):
        sess = AllinpayPlaceVersion.objects.filter(pid=attr.id).order_by("id")
        return sess.last().version if sess else ""


class AllinpayPlaceStatusSerializer(serializers.ModelSerializer):
    """场所状态"""

    id = IntegerField(help_text="场所ID")
    status = IntegerField(min_value=0, max_value=1, default=0, help_text="场所状态")

    class Meta:
        model = AllinpayPlaceList
        fields = ("id", "status")

    def validate_id(self, attr):
        try:
            AllinpayPlaceList.objects.get(id=attr)
        except BaseException as err:
            raise serializers.ValidationError("对象不存在")
        return attr


class AllinpayPlaceFeeSerializer(serializers.ModelSerializer):
    """场所手续费"""

    id = IntegerField(help_text="场所ID")
    fee = IntegerField(min_value=0, max_value=1000, default=0, help_text="场所手续费(千分比)")

    class Meta:
        model = AllinpayPlaceList
        fields = ("id", "fee")

    def validate_id(self, attr):
        try:
            AllinpayPlaceList.objects.get(id=attr)
        except BaseException as err:
            raise serializers.ValidationError("对象不存在")
        return attr


class AllinpayPlaceAuthSerializer(serializers.ModelSerializer):
    """场所管理员"""

    id = IntegerField(help_text="场所ID")
    auth = IntegerField(help_text="场所管理员ID")

    class Meta:
        model = AllinpayPlaceList
        fields = ("id", "auth")

    def validate_id(self, attr):
        try:
            AllinpayPlaceList.objects.get(id=attr)
        except BaseException as err:
            raise serializers.ValidationError("对象不存在")
        return attr

    def validate_auth(self, attr):
        try:
            AllinpayUserList.objects.get(id=attr)
        except BaseException as err:
            raise serializers.ValidationError("用户对象不存在")
        return attr


class PlaceModelsSetSerializer(serializers.ModelSerializer):
    """场所全局设置"""

    id = IntegerField(label="ID", read_only=True)
    parent = IntegerField(min_value=0, help_text="父级ID")
    name = CharField(required=False, help_text="名称")
    key = CharField(
        required=False,
        help_text="key",
        validators=[UniqueValidator(queryset=PlaceModelsSet.objects.all())],
    )

    class Meta:
        model = PlaceModelsSet
        fields = "__all__"


class PlaceModelsSetDictSerializer(serializers.Serializer):
    """场所配置dict"""

    # config = ListField(child=DictField())
    config = CharField(required=True, help_text="配置内容(json字符串)")

    class Meta:
        fields = "__all__"


# print(repr(PlaceModelsSetSerializer()))


class AllinpayTermListSerializer(serializers.ModelSerializer):
    """场所营收科目列表"""

    id = IntegerField(label="ID", read_only=True)
    name = CharField(required=True, help_text="场所收款名目名称")
    pid = IntegerField(required=True, help_text="场所ID")
    status = IntegerField(min_value=0, max_value=1, default=0, help_text="状态")
    detype = CharField(required=False, help_text="经营类型")
    # termsn = CharField(required=True, help_text="特征码")
    termsn = ChoiceField(
        choices=[x["key"] for x in settings.ALL_TERMSN_ITEMS],
        required=True,
        help_text="特征码",
    )
    bind = SerializerMethodField()

    class Meta:
        model = AllinpayTermList
        fields = "__all__"
        validators = [
            UniqueTogetherValidator(
                queryset=AllinpayTermList.objects.all(), fields=("name", "pid")
            )
        ]

    def validate_pid(self, attr):
        try:
            AllinpayPlaceList.objects.get(id=attr)
        except BaseException as err:
            raise serializers.ValidationError("场所对象不存在")
        return attr

    def get_bind(self, attr):
        try:
            sess = AllinpayPlaceList.objects.get(id=attr.auth)
        except BaseException as err:
            return ""
        return sess.name


class AllinpayBankListSerializer(serializers.ModelSerializer):
    """银行卡列表"""

    id = IntegerField(label="ID", read_only=True)
    bank = CharField(required=True, help_text="开户行")
    name = CharField(required=True, help_text="户名")
    cardcode = CharField(required=True, help_text="卡号")
    cbccode = CharField(required=True, help_text="联行号")
    status = IntegerField(min_value=0, max_value=1, default=0, help_text="状态")
    # auth = IntegerField(min_value=0, max_value=1, default=0, help_text="备用")
    # pid = IntegerField(min_value=0, help_text="场所ID")
    # bindpid = SerializerMethodField()
    # bindtid = SerializerMethodField()

    class Meta:
        model = AllinpayBankList
        fields = ["id", "bank", "name", "cardcode", "cbccode", "status"]

    # def validate_pid(self, attr):
    #     try:
    #         sess = AllinpayTermList.objects.get(id=attr.id)
    #     except BaseException as err:
    #         raise serializers.ValidationError("营收项目不存在")
    #     else:
    #         if not attr.pid == sess.pid:
    #             raise serializers.ValidationError("场所验证失败")
    #     return attr

    # def get_bindpid(self, attr):
    #     try:
    #         # sess = AllinpayTermList.objects.get(id=attr.id)
    #         obj = AllinpayPlaceList.objects.get(id=attr.pid)
    #     except BaseException as err:
    #         return ""
    #     return obj.name

    # def get_bindtid(self, attr):
    #     try:
    #         sess = AllinpayTermList.objects.get(id=attr.id)
    #     except BaseException as err:
    #         return ""
    #     return sess.name


class AllinpayTermBankSerializer(serializers.ModelSerializer):
    """绑定银行卡"""

    id = IntegerField(label="ID", read_only=True)
    tid = IntegerField(help_text="营收科目ID")
    bid = IntegerField(help_text="银行卡ID")
    ratio = IntegerField(min_value=0, default=0, help_text="分成权重(万分比)")

    class Meta:
        model = AllinpayTermBank
        fields = "__all__"
        validators = [
            UniqueTogetherValidator(
                queryset=AllinpayTermBank.objects.all(), fields=("tid", "bid")
            )
        ]

    def validate_tid(self, attr):
        if not attr in list(
            AllinpayTermList.objects.all().values_list("id", flat=True)
        ):
            raise serializers.ValidationError("营收科目ID错误")
        return attr

    def validate_bid(self, attr):
        if not attr in list(
            AllinpayBankList.objects.all().values_list("id", flat=True)
        ):
            raise serializers.ValidationError("银行卡ID错误")
        return attr


# print(repr(AllinpayTermBankSerializer()))


class AllinpayUserplaceListSerializer(serializers.ModelSerializer):
    """场所绑定用户"""

    id = IntegerField(label="ID", read_only=True)
    pid = IntegerField(required=True, help_text="场所ID")
    uid = IntegerField(required=True, help_text="用户ID")
    group = IntegerField(default=1, help_text="角色ID")
    binduid = SerializerMethodField(read_only=True)
    bindpid = SerializerMethodField(read_only=True)
    bindgroup = SerializerMethodField(read_only=True)

    class Meta:
        model = AllinpayUserplaceList
        fields = ("id", "uid", "pid", "group", "binduid", "bindpid", "bindgroup")
        validators = [
            UniqueTogetherValidator(
                queryset=AllinpayUserplaceList.objects.all(),
                fields=["uid", "pid", "group"],
            ),
        ]

    def validate_uid(self, attr):
        try:
            AllinpayUserList.objects.get(id=attr)
        except BaseException as err:
            raise serializers.ValidationError("用户对象不存在")
        return attr

    def validate_pid(self, attr):
        try:
            AllinpayPlaceList.objects.get(id=attr)
        except BaseException as err:
            if not attr == 0:
                raise serializers.ValidationError("场所对象不存在")
        return attr

    def validate_group(self, attr):
        try:
            AllinpayAuthGroup.objects.get(id=attr, pid__gt=0)
        except BaseException as err:
            raise serializers.ValidationError("角色对象不存在")
        return attr

    def get_binduid(self, attr):
        try:
            bind = AllinpayUserList.objects.get(id=attr.uid)
        except BaseException as err:
            raise serializers.ValidationError("用户对象不存在")
        from UserManager.serializers import AllinpayUserListSerializer

        return AllinpayUserListSerializer(bind, many=False).data

    def get_bindpid(self, attr):
        try:
            bind = AllinpayPlaceList.objects.get(id=attr.pid)
            return AllinpayPlaceInfoSerializer(bind, many=False).data
        except BaseException as err:
            if not attr.pid == 0:
                raise serializers.ValidationError("场所对象不存在")
            return {"id": 0, "name": "云后台"}

    def get_bindgroup(self, attr):
        try:
            bind = AllinpayAuthGroup.objects.get(id=attr.group)
        except BaseException as err:
            raise serializers.ValidationError("角色对象不存在")
        from UserManager.serializers import AllinpayAuthGroupSerializer

        return AllinpayAuthGroupSerializer(bind, many=False).data


class PlaceUserPermsSerializer(serializers.Serializer):
    """员工权限"""

    pid = IntegerField(min_value=0, help_text="场所ID")
    uid = IntegerField(help_text="员工ID")
    bind = SerializerMethodField()

    class Meta:
        fields = "__all__"

    def get_bind(self, attr):
        sess = []
        rid = AllinpayUserplaceList.objects.filter(**attr).values_list(
            "group", flat=True
        )
        if not rid:
            raise serializers.ValidationError("角色对象不存在")
        for i in rid:
            role = AllinpayAuthGroup.objects.get(id=i)
            perm = AllinpayAuthGroupPermissions.objects.filter(group_id=i).values_list(
                "permission_id", flat=True
            )

            rn = AllinpayAuthViews.objects.filter(id__in=perm).values(
                "id", "info", "act"
            )

            obj = model_to_dict(role)
            obj["bind"] = list(rn)

            sess.append(obj)

        return sess


class PlaceMyUserListSerializer(serializers.Serializer):
    """员工列表"""

    pid = IntegerField(min_value=0, help_text="场所ID")

    class Meta:
        fields = "__all__"

    def validate_pid(self, attr):
        try:
            AllinpayPlaceList.objects.get(id=attr)
        except BaseException as err:
            if not attr == 0:
                raise serializers.ValidationError("用户对象不存在")
        return attr


class PlaceLizhuInterfaceSerializer(serializers.ModelSerializer):
    """酒店接口"""

    id = IntegerField(label="ID", read_only=True)
    pid = IntegerField(
        help_text="场所ID",
        validators=[UniqueValidator(queryset=PlaceLizhuInterface.objects.all())],
    )
    hid = IntegerField(required=True, help_text="三方门店ID")
    name = CharField(allow_blank=True, required=False, help_text="三方门店名称")
    host = CharField(allow_blank=True, required=False, help_text="请求地址(利住:安全客户端)")
    appid = CharField(allow_blank=True, required=False, help_text="请求凭证")
    appkey = CharField(allow_blank=True, required=False, help_text="请求KEY")
    bind = SerializerMethodField()

    class Meta:
        model = PlaceLizhuInterface
        fields = "__all__"

    def validate_pid(self, attr):
        try:
            AllinpayPlaceList.objects.get(id=attr)
        except BaseException as err:
            raise serializers.ValidationError("场所对象不存在")
        return attr

    def get_bind(self, attr):
        try:
            sess = AllinpayPlaceList.objects.get(id=attr.pid)
        except BaseException as err:
            raise serializers.ValidationError("场所对象不存在")
        return sess.name


class PlacePospalInterfaceSerializer(serializers.ModelSerializer):
    """商超接口"""

    id = IntegerField(label="ID", read_only=True)
    pid = IntegerField(
        help_text="场所ID",
        validators=[UniqueValidator(queryset=PlacePospalInterface.objects.all())],
    )
    name = CharField(allow_blank=True, required=False, help_text="三方门店名称")
    host = CharField(allow_blank=True, required=False, help_text="请求地址")
    appid = CharField(allow_blank=True, required=False, help_text="请求凭证")
    appkey = CharField(allow_blank=True, required=False, help_text="请求KEY")
    bind = SerializerMethodField()

    class Meta:
        model = PlacePospalInterface
        fields = "__all__"

    def validate_pid(self, attr):
        try:
            AllinpayPlaceList.objects.get(id=attr)
        except BaseException as err:
            raise serializers.ValidationError("场所对象不存在")
        return attr

    def get_bind(self, attr):
        try:
            sess = AllinpayPlaceList.objects.get(id=attr.pid)
        except BaseException as err:
            raise serializers.ValidationError("场所对象不存在")
        return sess.name


class AllinpayBoxRegisterSerializer(serializers.ModelSerializer):
    """盒子注册"""

    id = IntegerField(
        min_value=1,
        help_text="场所ID",
        # label="ID",
        # read_only=True,
        # validators=[UniqueValidator(queryset=AllinpayBoxRegister.objects.all())],
    )
    hash = CharField(
        required=True,
        help_text="特征码hash",
        # validators=[UniqueValidator(queryset=AllinpayBoxRegister.objects.all())],
    )
    phone = CharField(required=True, help_text="手机号码")
    creattime = HiddenField(default=timezone.now)
    logintime = ReadOnlyField()

    class Meta:
        model = AllinpayBoxRegister
        fields = "__all__"

    def validate(self, attrs):
        try:
            AllinpayPlaceList.objects.get(id=attrs["id"], telephone=attrs["phone"])
        except BaseException as err:
            raise serializers.ValidationError({"register": "场所对象不存在或绑定手机错误"})
        return attrs


class AllinpayBoxLoginSerializer(serializers.ModelSerializer):
    """盒子登录"""

    id = IntegerField(label="ID", read_only=True)
    hash = CharField(required=True, help_text="特征码hash")

    creattime = ReadOnlyField()
    logintime = ReadOnlyField()

    class Meta:
        model = AllinpayBoxRegister
        fields = "__all__"


class AllinpayPlacecorpListSerializer(serializers.ModelSerializer):
    """连锁公司列表"""

    id = IntegerField(label="ID", read_only=True)
    status = IntegerField(min_value=0, max_value=1, default=0, help_text="状态")
    maximum = IntegerField(min_value=0, default=0, help_text="最大门店数")
    account = IntegerField(
        allow_null=True, min_value=0, required=False, help_text="公众号ID"
    )
    name = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        help_text="公司名称",
        validators=[UniqueValidator(queryset=AllinpayPlacecorpList.objects.all())],
    )
    logo = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="公司logo",
    )
    addre = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="公司地址",
    )
    super = RegexField(
        r"^1[23456789]\d{9}$",
        help_text="管理员账号(手机号)",
    )
    cutdate = DateField(allow_null=True, help_text="有效期")
    created = DateTimeField(default=CreateOnlyDefault(timezone.now), help_text="创建时间")
    modified = DateTimeField(default=timezone.now, help_text="编辑时间")

    class Meta:
        model = AllinpayPlacecorpList
        fields = "__all__"
        # exclude = ['id', 'title']  # 不显示指定的字段
        # depth = 1  # 会让你这些所有的外键关系变成read_only = True


class AllinpayPlaceroleListSerializer(serializers.ModelSerializer):
    """场所角色"""

    id = IntegerField(read_only=True)
    pid = IntegerField(allow_null=True, required=True, help_text="场所ID")
    name = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=True,
        help_text="角色名称",
    )
    place = SerializerMethodField()

    class Meta:
        model = AllinpayPlaceroleList
        fields = "__all__"
        validators = [
            UniqueTogetherValidator(
                queryset=AllinpayPlaceroleList.objects.all(), fields=("pid", "name")
            )
        ]

    def validate_pid(self, attr):
        try:
            AllinpayPlaceList.objects.get(id=attr)
        except BaseException as err:
            raise serializers.ValidationError("场所对象不存在")
        return attr

    def get_place(self, attr):
        try:
            sess = AllinpayPlaceList.objects.get(id=attr.pid)
        except BaseException as err:
            raise serializers.ValidationError("场所对象不存在")
        return model_to_dict(sess)


class AllinpayCallmePostSerializer(serializers.ModelSerializer):
    """员工呼叫类型"""

    callpost = SerializerMethodField()

    class Meta:
        model = AllinpayCallmePost
        fields = "__all__"

    def get_callpost(self, attr):
        try:
            sess = AllinpayCallmeConf.objects.get(id=attr.cid)
        except BaseException as err:
            return {}
        return model_to_dict(sess)


class AllinpayPlacestaffListSerializer(serializers.ModelSerializer):
    """场所员工"""

    id = IntegerField(label="ID", read_only=True)
    status = IntegerField(
        allow_null=True,
        max_value=1,
        min_value=0,
        default=1,
        help_text="状态",
    )
    sid = IntegerField(
        allow_null=True,
        required=True,
        help_text="员工ID",
    )
    pid = IntegerField(
        allow_null=True,
        required=True,
        help_text="场所ID",
    )
    created = DateTimeField(default=CreateOnlyDefault(timezone.now), help_text="创建时间")
    modifed = DateTimeField(default=timezone.now, help_text="编辑时间")
    star = IntegerField(min_value=0, required=False, help_text="星级")
    place = SerializerMethodField()
    staff = SerializerMethodField()
    extend = SerializerMethodField()
    role = SerializerMethodField()
    post = SerializerMethodField()
    work = SerializerMethodField()
    job = SerializerMethodField()
    roles = SerializerMethodField()
    team = SerializerMethodField()

    class Meta:
        model = AllinpayPlacestaffList
        fields = "__all__"
        validators = [
            UniqueTogetherValidator(
                queryset=AllinpayPlacestaffList.objects.all(), fields=("sid", "pid")
            )
        ]

    def validate_pid(self, attr):
        try:
            AllinpayPlaceList.objects.get(id=attr)
        except BaseException as err:
            raise serializers.ValidationError("场所对象不存在")
        return attr

    def validate_sid(self, attr):
        try:
            AllinpayStaffList.objects.get(id=attr)
        except BaseException as err:
            raise serializers.ValidationError("员工对象不存在")
        return attr

    def get_place(self, attr):
        try:
            sess = AllinpayPlaceList.objects.get(id=attr.pid)
        except BaseException as err:
            raise serializers.ValidationError("场所对象不存在")
        return model_to_dict(sess)

    def get_staff(self, attr):
        try:
            sess = AllinpayStaffList.objects.get(id=attr.sid)
        except BaseException as err:
            raise serializers.ValidationError("员工对象不存在")
        return model_to_dict(sess)

    def get_extend(self, attr):
        try:
            sess = AllinpayPlacestaffExtend.objects.get(id=attr.id)
        except BaseException as err:
            # raise serializers.ValidationError("员工扩展信息不存在")
            return None
        return model_to_dict(sess)

    def get_role(self, attr):
        rid = list(
            AllinpayPlacestaffRole.objects.filter(
                pid=attr.pid, sid=attr.sid
            ).values_list("rid", flat=True)
        )
        for i in range(len(rid)):
            rid[i] = model_to_dict(AllinpayPlaceroleList.objects.get(id=rid[i]))
        return rid

    def get_roles(self, attr):
        sess = AllinpayPlacestaffRoleSerializer(
            AllinpayPlacestaffRole.objects.filter(pid=attr.pid, sid=attr.sid), many=True
        ).data
        for i in range(len(sess)):
            sess[i]["name"] = AllinpayPlaceroleList.objects.get(id=sess[i]["rid"]).name
        return sess

    def get_post(self, attr):
        sess = list(
            AllinpayCallmePostSerializer(
                AllinpayCallmePost.objects.filter(sid=attr.sid, pid=attr.pid), many=True
            ).data
        )
        return sess

    def get_work(self, attr):
        try:
            isPost = AllinpayPlacestaffPost.objects.get(id=attr.id)
        except BaseException as err:
            return 0
        else:
            return isPost.status

    def get_job(self, attr):
        try:
            isPost = AllinpayPlacestaffPost.objects.get(id=attr.id)
        except BaseException as err:
            return {}
        else:
            return model_to_dict(isPost)

    def get_team(self, attr):
        try:
            r = AllinpayStaffteamList.objects.get(
                pid=attr.pid, staffs__icontains=attr.sid
            )
        except BaseException as err:
            return None
        else:
            return r.name


class AllinpayPlaceviewsCreatSerializer(serializers.Serializer):
    """创建视图"""

    name = CharField(
        required=True,
        help_text="视图名称",
    )
    info = CharField(
        required=True,
        help_text="权限说明",
    )
    act = ChoiceField(
        choices=["GET", "POST", "PUT", "PATCH", "DELETE"],
        required=True,
        help_text="请求方法",
    )

    class Meta:
        fields = "__all__"


class AllinpayPlaceviewsListSerializer(serializers.ModelSerializer):
    """场所视图"""

    id = IntegerField(label="ID", read_only=True)
    name = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=True,
        help_text="视图名称",
    )
    info = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=True,
        help_text="权限说明",
    )
    act = ChoiceField(
        choices=["GET", "POST", "PUT", "PATCH", "DELETE"],
        required=True,
        help_text="请求方法",
    )

    class Meta:
        model = AllinpayPlaceviewsList
        fields = "__all__"
        validators = [
            UniqueTogetherValidator(
                queryset=AllinpayPlaceviewsList.objects.all(), fields=("name", "act")
            )
        ]


class AllinpayPlaceviewsListYunSerializer(serializers.ModelSerializer):
    """场所视图"""

    id = IntegerField(label="ID", read_only=True)
    name = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=True,
        help_text="视图名称",
    )
    info = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=True,
        help_text="权限说明",
    )
    act = ChoiceField(
        choices=["GET", "POST", "PUT", "PATCH", "DELETE"],
        required=True,
        help_text="请求方法",
    )
    staff = ChoiceField(
        choices=[0, 1, 2],
        required=False,
        help_text="视图类型",
    )

    class Meta:
        model = AllinpayAuthViews
        fields = "__all__"
        validators = [
            UniqueTogetherValidator(
                queryset=AllinpayAuthViews.objects.all(), fields=("name", "act")
            )
        ]


class AllinpayPlacestaffRoleSerializer(serializers.ModelSerializer):
    """场所员工角色"""

    id = IntegerField(label="ID", read_only=True)
    pid = IntegerField(
        allow_null=True,
        required=True,
        help_text="场所ID",
    )
    sid = IntegerField(
        allow_null=True,
        required=True,
        help_text="员工ID",
    )
    rid = IntegerField(
        allow_null=True,
        required=True,
        help_text="角色ID",
    )
    place = SerializerMethodField()
    staff = SerializerMethodField()
    myrole = SerializerMethodField()

    class Meta:
        model = AllinpayPlacestaffRole
        fields = "__all__"
        validators = [
            UniqueTogetherValidator(
                queryset=AllinpayPlacestaffRole.objects.all(),
                fields=("pid", "sid", "rid"),
            )
        ]

    def validate_pid(self, attr):
        try:
            AllinpayPlaceList.objects.get(id=attr)
        except BaseException as err:
            raise serializers.ValidationError("场所对象不存在")
        return attr

    def validate_sid(self, attr):
        try:
            AllinpayStaffList.objects.get(id=attr)
        except BaseException as err:
            raise serializers.ValidationError("员工对象不存在")
        return attr

    def validate_rid(self, attr):
        try:
            AllinpayPlaceroleList.objects.get(id=attr)
        except BaseException as err:
            raise serializers.ValidationError("角色对象不存在")
        return attr

    def get_place(self, attr):
        try:
            sess = AllinpayPlaceList.objects.get(id=attr.pid)
        except BaseException as err:
            raise serializers.ValidationError("场所对象不存在")
        return model_to_dict(sess)

    def get_staff(self, attr):
        try:
            sess = AllinpayStaffList.objects.get(id=attr.sid)
        except BaseException as err:
            raise serializers.ValidationError("员工对象不存在")
        return model_to_dict(sess)

    def get_myrole(self, attr):
        try:
            sess = AllinpayPlaceroleList.objects.get(id=attr.rid)
        except BaseException as err:
            raise serializers.ValidationError("角色对象不存在")
        return model_to_dict(sess)


class AllinpayPlacerolePermSerializer(serializers.ModelSerializer):
    """场所角色权限"""

    id = IntegerField(label="ID", read_only=True)
    rid = IntegerField(
        allow_null=True,
        max_value=2147483647,
        min_value=-2147483648,
        required=True,
        help_text="角色ID",
    )
    vid = IntegerField(
        allow_null=True,
        max_value=2147483647,
        min_value=-2147483648,
        required=True,
        help_text="权限ID",
    )
    myrole = SerializerMethodField()
    myperm = SerializerMethodField()

    class Meta:
        model = AllinpayPlacerolePerm
        fields = "__all__"
        validators = [
            UniqueTogetherValidator(
                queryset=AllinpayPlacerolePerm.objects.all(), fields=("rid", "vid")
            )
        ]

    def validate_rid(self, attr):
        try:
            AllinpayPlaceroleList.objects.get(id=attr)
        except BaseException as err:
            raise serializers.ValidationError("角色对象不存在")
        return attr

    def validate_vid(self, attr):
        try:
            AllinpayPlaceviewsList.objects.get(id=attr)
        except BaseException as err:
            raise serializers.ValidationError("权限对象不存在")
        return attr

    def get_myrole(self, attr):
        try:
            sess = AllinpayPlaceroleList.objects.get(id=attr.rid)
        except BaseException as err:
            # raise serializers.ValidationError("角色对象不存在")
            return {}
        return model_to_dict(sess)

    def get_myperm(self, attr):
        try:
            sess = AllinpayPlaceviewsList.objects.get(id=attr.vid)
        except BaseException as err:
            # raise serializers.ValidationError("权限对象不存在")
            return {}
        return model_to_dict(sess)


class AllinpayPlacerolePermYunSerializer(serializers.ModelSerializer):
    """场所角色权限"""

    id = IntegerField(label="ID", read_only=True)
    rid = IntegerField(
        allow_null=True,
        max_value=2147483647,
        min_value=-2147483648,
        required=True,
        help_text="角色ID",
    )
    vid = IntegerField(
        allow_null=True,
        max_value=2147483647,
        min_value=-2147483648,
        required=True,
        help_text="权限ID",
    )
    myrole = SerializerMethodField()
    myperm = SerializerMethodField()

    class Meta:
        model = AllinpayPlacerolePermYun
        fields = "__all__"
        validators = [
            UniqueTogetherValidator(
                queryset=AllinpayPlacerolePermYun.objects.all(), fields=("rid", "vid")
            )
        ]

    def validate_rid(self, attr):
        try:
            AllinpayPlaceroleList.objects.get(id=attr)
        except BaseException as err:
            raise serializers.ValidationError("角色对象不存在")
        return attr

    def validate_vid(self, attr):
        try:
            AllinpayAuthViews.objects.get(id=attr)
        except BaseException as err:
            raise serializers.ValidationError("权限对象不存在")
        return attr

    def get_myrole(self, attr):
        try:
            sess = AllinpayPlaceroleList.objects.get(id=attr.rid)
        except BaseException as err:
            # raise serializers.ValidationError("角色对象不存在")
            return {}
        return model_to_dict(sess)

    def get_myperm(self, attr):
        try:
            sess = AllinpayAuthViews.objects.get(id=attr.vid)
        except BaseException as err:
            # raise serializers.ValidationError("权限对象不存在")
            return {}
        return model_to_dict(sess)


class AllinpayPlacestaffExtendSerializer(serializers.ModelSerializer):
    """场所用户扩展信息"""

    id = IntegerField(label="ID", read_only=True)
    metier = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="专长",
    )
    idcarda = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="身份证正面",
    )
    idcardb = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="身份证背面",
    )
    applya = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="入职申请A",
    )
    applyb = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="入职申请B",
    )
    contracta = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="劳动合同",
    )
    contractb = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="劳务合同",
    )
    mobile = IntegerField(
        allow_null=True,
        max_value=1,
        min_value=0,
        default=0,
        help_text="移动端登录",
    )
    platform = IntegerField(
        allow_null=True,
        max_value=1,
        min_value=0,
        default=0,
        help_text="吧台端登录",
    )
    modifed = DateTimeField(default=timezone.now, help_text="编辑时间")

    class Meta:
        model = AllinpayPlacestaffExtend
        fields = "__all__"


class AllinpayPlaceStaffPostSerializer(serializers.ModelSerializer):
    """场所员工在岗"""

    id = IntegerField(
        help_text="场所员工绑定ID",
        validators=[UniqueValidator(queryset=AllinpayPlacestaffPost.objects.all())],
    )
    status = IntegerField(max_value=1, min_value=0, help_text="状态")

    class Meta:
        model = AllinpayPlacestaffPost
        fields = "__all__"

    # def validate(self, attrs):
    #     try:
    #         AllinpayPlacestaffList.objects.get(id=attrs["id"], telephone=attrs["phone"])
    #     except BaseException as err:
    #         raise serializers.ValidationError({"register": "场所对象不存在或绑定手机错误"})
    #     return attrs


class AllinpayPlaceGradeSerializer(serializers.ModelSerializer):
    """场所班次"""

    id = IntegerField(label="ID", read_only=True)
    pid = IntegerField(allow_null=True, required=True, help_text="场所ID")
    name = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=True,
        help_text="班次名称",
    )
    star = TimeField(required=True, help_text="开始时间")
    end = TimeField(required=True, help_text="结束时间")
    sky = IntegerField(read_only=True, help_text="是否跨天")

    class Meta:
        model = AllinpayPlaceGrade
        fields = "__all__"
        validators = [
            UniqueTogetherValidator(
                queryset=AllinpayPlaceGrade.objects.all(), fields=("pid", "name")
            )
        ]


class AllinpayPlaceGradeListSerializer(serializers.ModelSerializer):
    """排班表"""

    id = IntegerField(label="ID", read_only=True)
    pid = IntegerField(allow_null=True, required=True, help_text="场所ID")
    grade = IntegerField(allow_null=True, required=True, help_text="班次ID")
    staff = IntegerField(allow_null=True, required=True, help_text="员工ID")
    today = DateField(required=True, help_text="日期")
    currentime = DateTimeField(read_only=True, help_text="编辑日期")

    places = SerializerMethodField()
    grades = SerializerMethodField()
    staffs = SerializerMethodField()

    class Meta:
        model = AllinpayPlaceGradeList
        fields = "__all__"
        validators = [
            UniqueTogetherValidator(
                queryset=AllinpayPlaceGradeList.objects.all(),
                fields=("pid", "grade", "today"),
            )
        ]

    def get_places(self, attr):
        try:
            sess = AllinpayPlaceList.objects.get(id=attr.pid)
        except BaseException as err:
            return ""
        return sess.name

    def get_grades(self, attr):
        try:
            sess = AllinpayPlaceGrade.objects.get(id=attr.grade)
        except BaseException as err:
            return ""
        return sess.name

    def get_staffs(self, attr):
        try:
            sess = AllinpayStaffList.objects.get(id=attr.staff)
        except BaseException as err:
            return ""
        return sess.basename

    def validate(self, attrs):
        res = dict(attrs)
        try:
            r = AllinpayPlaceGrade.objects.get(id=res.get("grade"), pid=res.get("pid"))
        except BaseException as err:
            raise serializers.ValidationError({"grade": "场所班次错误"})
        try:
            r = AllinpayPlacestaffList.objects.get(
                pid=res.get("pid"), sid=res.get("staff"), status=1
            )
        except BaseException as err:
            raise serializers.ValidationError({"staff": "场所员工错误"})
        return attrs


class AllinpayRawardListSerializer(serializers.ModelSerializer):
    """奖励列表"""

    id = IntegerField(label="ID", read_only=True)
    pid = IntegerField(help_text="场所ID")
    raid = IntegerField(default=0, help_text="模板ID")
    integral = IntegerField(help_text="分值")
    intetype = IntegerField(help_text="分值类型ID")
    name = CharField(allow_blank=True, allow_null=True, max_length=255, help_text="名称")

    typename = SerializerMethodField()
    model = SerializerMethodField()

    class Meta:
        model = AllinpayRawardList
        fields = "__all__"

    def get_model(self, attr):
        try:
            r = AllinpayRawardModel.objects.get(id=attr.raid)
        except BaseException as err:
            return None
        else:
            return model_to_dict(r)

    def get_typename(self, attr):
        """类型"""
        try:
            r = AllinpayIntegralList.objects.get(id=attr.intetype)
        except BaseException as err:
            return None
        else:
            from mysqldb.serializers import GlobalConfIntegralListSerializer

            return GlobalConfIntegralListSerializer(r).data

    def validate_pid(self, attr):
        if not attr in list(
            AllinpayPlaceList.objects.filter(status=1).values_list("id", flat=True)
        ):
            raise serializers.ValidationError("场所ID错误")
        return attr

    # def validate_raid(self, attr):
    #     if not attr in list(
    #         AllinpayRawardModel.objects.filter(status=1).values_list("id", flat=True)
    #     ):
    #         raise serializers.ValidationError("模板ID错误")
    #     return attr

    def validate_intetype(self, attr):
        if attr == 1:
            return attr
        if not attr in list(
            AllinpayIntegralList.objects.filter(status=1).values_list("id", flat=True)
        ):
            raise serializers.ValidationError("分值类型ID错误")
        return attr

    def validate(self, attrs):
        try:
            r = AllinpayIntegralList.objects.get(id=attrs["intetype"])
        except BaseException as err:
            raise serializers.ValidationError("分值类型错误")
        else:
            if r.total and attrs["integral"] < 0:
                raise serializers.ValidationError("该类分值为累加，不能为负数。")
        return attrs


class AllinpayRawardModelSerializer(serializers.ModelSerializer):
    """奖励模板"""

    id = IntegerField(label="ID", read_only=True)
    pid = IntegerField(help_text="场所ID")
    name = CharField(allow_blank=True, allow_null=True, max_length=255, help_text="名称")
    notes = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="备注",
    )
    status = IntegerField(max_value=1, min_value=0, default=1, help_text="状态")

    onlist = SerializerMethodField()

    class Meta:
        model = AllinpayRawardModel
        fields = "__all__"
        validators = [
            UniqueTogetherValidator(
                queryset=AllinpayRawardModel.objects.all(), fields=("name", "pid")
            )
        ]

    def get_onlist(self, attr):
        """分值"""
        try:
            r = AllinpayRawardList.objects.filter(raid=attr.id)
        except BaseException as err:
            return []
        else:
            return AllinpayRawardListSerializer(r, many=True).data

    def validate_pid(self, attr):
        if not attr in list(
            AllinpayPlaceList.objects.all().values_list("id", flat=True)
        ):
            raise serializers.ValidationError("场所ID错误")
        return attr


class AllinpayPlacecameraListSerializer(serializers.ModelSerializer):
    """场所监控列表"""

    id = IntegerField(label="ID", read_only=True)
    pid = IntegerField(help_text="场所ID")
    brand = ChoiceField(choices=("海康威视", "浙江大华"), allow_blank=True, help_text="监控品牌")
    model = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="型号",
    )
    name = CharField(
        allow_blank=True, allow_null=True, max_length=255, help_text="名称标识"
    )
    # pact = ChoiceField(choices=("http", "https"), allow_blank=True, help_text="请求协议")
    ipadd = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        help_text="IP地址",
    )
    port = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        help_text="端口",
    )
    user = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        help_text="用户名",
    )
    pawd = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        help_text="密码",
    )
    status = IntegerField(default=1, max_value=1, min_value=0, help_text="状态")

    class Meta:
        model = AllinpayPlacecameraList
        # fields = "__all__"
        exclude = ["pact"]
        validators = [
            UniqueTogetherValidator(
                queryset=AllinpayPlacecameraList.objects.all(), fields=("pid", "name")
            )
        ]

    def validate_pid(self, attr):
        if not attr in list(
            AllinpayPlaceList.objects.all().values_list("id", flat=True)
        ):
            raise serializers.ValidationError("场所ID错误")
        return attr


class AllinpayPlaceWorkitemSerializer(serializers.ModelSerializer):
    """场所工作项模板列表"""

    id = IntegerField(label="ID", read_only=True)
    types = IntegerField(help_text="类型")
    title = CharField(allow_blank=True, allow_null=True, max_length=255, help_text="标题")
    ismoon = fields.MultipleChoiceField(
        allow_null=True,
        choices=list(range(1, 32)),
        default=set(),
        help_text="月工作日([1-31])",
    )
    isweek = fields.MultipleChoiceField(
        allow_null=True, choices=list(range(7)), default=set(), help_text="周工作日([0-6])"
    )
    examples = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="照片",
    )
    content = CharField(
        allow_blank=True,
        allow_null=True,
        required=False,
        help_text="工作内容",
        style={"base_template": "textarea.html"},
    )
    star = TimeField(allow_null=True, help_text="开始时间")
    over = TimeField(allow_null=True, help_text="结束时间")
    alarm = TimeField(allow_null=True, help_text="提醒时间")
    submit = HiddenField(default="00:00:00", help_text="提交时间")
    autodelivery = IntegerField(default=0, max_value=1, min_value=0, help_text="是否自动分配")
    autodraw = IntegerField(default=0, max_value=1, min_value=0, help_text="是否自动接单")
    gradeappoint = IntegerField(default=0, max_value=1, min_value=0, help_text="按排班分配")
    jobappoint = IntegerField(default=0, max_value=1, min_value=0, help_text="按岗位分配")
    integral = IntegerField(
        read_only=True, default=0, max_value=1, min_value=0, help_text="奖励积分类型(禁用)"
    )
    status = IntegerField(default=0, max_value=1, min_value=0, help_text="状态")

    pid = IntegerField(help_text="场所ID")
    isloop = IntegerField(
        read_only=True, default=0, max_value=1, min_value=0, help_text="是否循环(禁用)"
    )

    camera = ListField(
        child=CharField(), allow_empty=True, required=False, help_text="抓拍"
    )
    # raward = ListField(
    #     child=CharField(), allow_empty=True, required=False, help_text="奖励模板(停用)"
    # )
    onrole = ListField(
        child=CharField(), allow_empty=True, required=False, help_text="执行岗位(角色)"
    )
    onstaff = ListField(
        child=CharField(), allow_empty=True, required=False, help_text="执行人"
    )
    ongrade = ListField(
        child=CharField(), allow_empty=True, required=False, help_text="班次"
    )

    # outtype = IntegerField(required=False, help_text="超时分值类型(停用)")
    # subtype = IntegerField(required=False, help_text="未提交分值类型(停用)")
    isout = IntegerField(default=0, max_value=1, min_value=0, help_text="是否检测超时")
    outinter = IntegerField(default=0, help_text="超时分值")
    issub = IntegerField(default=0, max_value=1, min_value=0, help_text="是否检测未提交")
    subinter = IntegerField(default=0, help_text="未提交分值")
    len0 = IntegerField(min_value=1, help_text="奖励积分类型")

    typeName = SerializerMethodField()
    pidName = SerializerMethodField()
    cameraName = SerializerMethodField()
    rawardName = SerializerMethodField()
    roleName = SerializerMethodField()
    staffName = SerializerMethodField()
    gradeName = SerializerMethodField()
    jifenName = SerializerMethodField()

    class Meta:
        model = AllinpayPlaceworkitemModel
        # fields = "__all__"
        exclude = ["outtype", "subtype", "raward"]

    def get_jifenName(self, attr):
        try:
            r = AllinpayIntegralList.objects.get(id=attr.len0)
        except BaseException as err:
            return ""
        else:
            return r.name

    def get_typeName(self, attr):
        try:
            r = AllinpayWorkitenTypes.objects.get(id=attr.types)
        except BaseException as err:
            return ""
        else:
            return r.name

    def get_pidName(self, attr):
        try:
            r = AllinpayPlaceList.objects.get(id=attr.pid)
        except BaseException as err:
            return ""
        else:
            return r.basename

    def get_rawardName(self, attr):
        """奖励模板"""
        # print(attr.raward, eval(attr.raward))
        try:
            r = AllinpayRawardList.objects.filter(
                id__in=list(eval(attr.raward))
            ).values("id", "name")
        except BaseException as err:
            return []
        else:
            return list(r)

    def get_cameraName(self, attr):
        """摄像头"""
        try:
            r = AllinpayPlacecameraList.objects.filter(
                id__in=list(eval(attr.camera))
            ).values("id", "name")
        except BaseException as err:
            return []
        else:
            return list(r)

    def get_roleName(self, attr):
        """角色"""
        try:
            r = AllinpayPlaceroleList.objects.filter(
                id__in=list(eval(attr.onrole))
            ).values("id", "name")
        except BaseException as err:
            return []
        else:
            return list(r)

    def get_staffName(self, attr):
        """员工"""
        try:
            r = AllinpayStaffList.objects.filter(
                id__in=list(eval(attr.onstaff))
            ).values("id", "basename")
        except BaseException as err:
            return []
        else:
            return list(r)

    def get_gradeName(self, attr):
        """班次"""
        try:
            r = AllinpayPlaceGrade.objects.filter(
                id__in=list(eval(attr.ongrade))
            ).values("id", "name")
        except BaseException as err:
            return []
        else:
            return list(r)

    def validate_types(self, attr):
        if not attr in list(
            AllinpayWorkitenTypes.objects.all().values_list("id", flat=True)
        ):
            raise serializers.ValidationError("作业类型")
        return attr

    def validate_pid(self, attr):
        if not attr in list(
            AllinpayPlaceList.objects.all().values_list("id", flat=True)
        ):
            raise serializers.ValidationError("场所ID错误")
        return attr

    def validate_outtype(self, attr):
        if not attr in list(
            AllinpayIntegralList.objects.all().values_list("id", flat=True)
        ):
            raise serializers.ValidationError("分值类型ID错误")
        return attr

    def validate_subtype(self, attr):
        if not attr in list(
            AllinpayIntegralList.objects.all().values_list("id", flat=True)
        ):
            raise serializers.ValidationError("分值类型ID错误")
        return attr

    def validate_len0(self, attr):
        if not attr in list(
            AllinpayIntegralList.objects.all().values_list("id", flat=True)
        ):
            raise serializers.ValidationError("分值类型ID错误")
        return attr

    def validate_camera(self, attr):
        x = list(AllinpayPlacecameraList.objects.all().values_list("id", flat=True))
        # print(attr, x)
        for i in attr:
            if not int(i) in x:
                raise serializers.ValidationError("camera ID 不合法")
        return attr

    def validate_raward(self, attr):
        x = list(AllinpayRawardList.objects.all().values_list("id", flat=True))
        for i in attr:
            if not int(i) in x:
                raise serializers.ValidationError("raward ID 不合法")
        return attr

    def validate_onrole(self, attr):
        x = list(AllinpayPlaceroleList.objects.all().values_list("id", flat=True))
        for i in attr:
            if not int(i) in x:
                raise serializers.ValidationError("onrole ID 不合法")
        return attr

    def validate_onstaff(self, attr):
        x = list(AllinpayPlacestaffList.objects.all().values_list("sid", flat=True))
        for i in attr:
            if not int(i) in x:
                raise serializers.ValidationError("onstaff ID 不合法")
        return attr

    def validate_ongrade(self, attr):
        x = list(AllinpayPlaceGrade.objects.all().values_list("id", flat=True))
        for i in attr:
            if not int(i) in x:
                raise serializers.ValidationError("ongrade ID 不合法")
        return attr

    def validate(self, attrs):
        sess = attrs.copy()

        if sess.get("raward"):
            """奖励模板"""
            a = AllinpayRawardList.objects.filter(
                pid=sess.get("pid"), id__in=list(sess["raward"])
            )
            if len(a) < len(list(sess["raward"])):
                raise serializers.ValidationError({"raward": "分值模板错误"})

        if sess.get("onrole"):
            """角色"""
            a = AllinpayPlaceroleList.objects.filter(
                pid=sess.get("pid"), id__in=list(sess["onrole"])
            )
            if len(a) < len(list(sess["onrole"])):
                raise serializers.ValidationError({"onrole": "角色错误"})

        if sess.get("onstaff"):
            """员工"""
            a = AllinpayPlacestaffList.objects.filter(
                pid=sess.get("pid"), sid__in=list(sess["onstaff"]), status=1
            )
            if len(a) < len(list(sess["onstaff"])):
                raise serializers.ValidationError({"onstaff": "员工错误"})

        if sess.get("ongrade"):
            """班次"""
            a = AllinpayPlaceGrade.objects.filter(
                Q(pid=sess.get("pid"))
                & Q(id__in=list(sess["ongrade"]))
                & Q(
                    Q(star__lte=sess.get("over"))  # 结束时间 > 上班时间
                    | Q(end__gte=sess.get("star"))  # 开始时间 < 下班时间
                )
            )
            if len(a) < len(list(sess["ongrade"])):
                raise serializers.ValidationError({"ongrade": "校验班次匹配错误"})

        if sess.get("gradeappoint") and not sess.get("ongrade"):
            raise serializers.ValidationError({"ongrade": "排班分配,班次错误"})

        if sess.get("jobappoint") and not sess.get("onrole"):
            raise serializers.ValidationError({"onrole": "岗位分配,角色错误"})

        # if sess.get("isout"):
        #     if not sess.get("outtype"):
        #         raise serializers.ValidationError({"outtype": "超时分值类型不能为空"})
        #     try:
        #         a = AllinpayIntegralList.objects.get(id=sess.get("outtype"))
        #     except BaseException as err:
        #         raise serializers.ValidationError({"outtype": "超时分值类型不存在"})
        #     else:
        #         if a.total and sess.get("outinter") < 0:
        #             raise serializers.ValidationError({"outtype": "超时分值类型只能累加"})
        # if sess.get("issub"):
        #     if not sess.get("subtype"):
        #         raise serializers.ValidationError({"subtype": "未提交分值类型不能为空"})
        #     try:
        #         a = AllinpayIntegralList.objects.get(id=sess.get("subtype"))
        #     except BaseException as err:
        #         raise serializers.ValidationError({"subtype": "未提交分值类型不存在"})
        #     else:
        #         if a.total and sess.get("subinter") < 0:
        #             raise serializers.ValidationError({"subtype": "未提交分值类型只能累加"})
        return sess

    def to_representation(self, instance):
        """mysql to python"""
        ret = super(AllinpayPlaceWorkitemSerializer, self).to_representation(instance)
        # print("查询:", ret)
        if ret.get("ismoon"):
            ret["ismoon"] = [
                x for x in list(eval(str(instance.ismoon))) if type(x) == int
            ]
        if ret.get("isweek"):
            ret["isweek"] = [
                x for x in list(eval(str(instance.isweek))) if type(x) == int
            ]

        if ret.get("camera"):
            ret["camera"] = [
                int(x) for x in list(eval(str(instance.camera))) if type(x) == str
            ]
        if ret.get("raward"):
            ret["raward"] = [
                int(x) for x in list(eval(str(instance.raward))) if type(x) == str
            ]
        if ret.get("onrole"):
            ret["onrole"] = [
                int(x) for x in list(eval(str(instance.onrole))) if type(x) == str
            ]
        if ret.get("onstaff"):
            ret["onstaff"] = [
                int(x) for x in list(eval(str(instance.onstaff))) if type(x) == str
            ]
        if ret.get("ongrade"):
            ret["ongrade"] = [
                int(x) for x in list(eval(str(instance.ongrade))) if type(x) == str
            ]

        return ret


class AllinpayPlaceWorkitemFromModelsSerializer(serializers.Serializer):
    """根据公共模板创建工作项"""

    mid = IntegerField(help_text="模板ID")
    pid = IntegerField(help_text="场所ID")

    class Meta:
        fields = "__all__"

    def validate_mid(self, attr):
        if not attr in list(
            AllinpayWorkitemModel.objects.filter(status=1).values_list("id", flat=True)
        ):
            raise serializers.ValidationError("模板ID错误")
        return attr

    def validate_pid(self, attr):
        if not attr in list(
            AllinpayPlaceList.objects.filter(status=1).values_list("id", flat=True)
        ):
            raise serializers.ValidationError("场所ID错误")
        return attr


class AllinpayPlaceWorkitemToModelsSerializer(serializers.Serializer):
    """根据工作项事务创建场所模板"""

    mid = IntegerField(help_text="模板ID")
    pid = IntegerField(help_text="场所ID")

    class Meta:
        fields = "__all__"

    def validate_mid(self, attr):
        if not attr in list(
            AllinpayWorkitemModel.objects.filter(status=1).values_list("id", flat=True)
        ):
            raise serializers.ValidationError("模板ID错误")
        return attr

    def validate_pid(self, attr):
        if not attr in list(
            AllinpayPlaceList.objects.filter(status=1).values_list("id", flat=True)
        ):
            raise serializers.ValidationError("场所ID错误")
        return attr


class AllinpayPlaceworkitemListSerializer(serializers.ModelSerializer):
    """场所工作项事务列表"""

    id = IntegerField(label="ID", read_only=True)
    types = IntegerField(help_text="类型")
    title = CharField(allow_blank=True, allow_null=True, max_length=255, help_text="标题")
    examples = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="照片",
    )
    content = CharField(
        allow_blank=True,
        allow_null=True,
        required=False,
        help_text="工作内容",
        style={"base_template": "textarea.html"},
    )
    star = TimeField(allow_null=True, help_text="开始时间")
    over = TimeField(allow_null=True, help_text="结束时间")
    alarm = TimeField(allow_null=True, help_text="提醒时间")
    status = IntegerField(default=0, max_value=1, min_value=0, help_text="状态")
    pid = IntegerField(help_text="场所ID")

    camera = ListField(
        allow_null=True, child=CharField(), required=False, help_text="抓拍"
    )
    raward = ListField(
        allow_null=True, child=CharField(), required=False, help_text="奖励模板"
    )
    onstaff = IntegerField(help_text="执行人")
    currentdate = DateField(allow_null=True, required=False, help_text="事务日期")

    isout = IntegerField(default=0, max_value=1, min_value=0, help_text="是否检测超时")
    outtype = IntegerField(
        allow_null=True, required=False, help_text="超时分值类型(停用)(是否超时)"
    )
    outinter = IntegerField(default=0, help_text="超时分值")
    issub = IntegerField(default=0, max_value=1, min_value=0, help_text="是否检测未提交")
    subtype = IntegerField(allow_null=True, required=False, help_text="未提交分值类型(停用)")
    subinter = IntegerField(default=0, help_text="未提交分值")

    len0 = IntegerField(min_value=1, help_text="奖励积分类型")

    typeName = SerializerMethodField()
    pidName = SerializerMethodField()
    cameraName = SerializerMethodField()
    rawardName = SerializerMethodField()
    staffName = SerializerMethodField()

    submitObj = SerializerMethodField()
    checkObj = SerializerMethodField()

    jifenName = SerializerMethodField()

    class Meta:
        model = AllinpayPlaceworkitemList
        fields = [
            "id",
            "types",
            "title",
            "content",
            "examples",
            "star",
            "over",
            "alarm",
            "camera",
            "status",
            "pid",
            "raward",
            "onstaff",
            "currentdate",
            "isout",
            "outtype",
            "outinter",
            "issub",
            "subtype",
            "subinter",
            "typeName",
            "pidName",
            "cameraName",
            "rawardName",
            "staffName",
            "submitObj",
            "checkObj",
            "len0",
            "len1",
            "len2",
            "len3",
            "len4",
            "len5",
            "len6",
            "len7",
            "len8",
            "len9",
            "jifenName",
        ]
        # exclude = [
        #     "ismoon",
        #     "isweek",
        #     "autodelivery",
        #     "autodraw",
        #     "gradeappoint",
        #     "jobappoint",
        #     "isloop",
        # ]

    def get_jifenName(self, attr):
        try:
            r = AllinpayIntegralList.objects.get(id=attr.len0)
        except BaseException as err:
            return ""
        else:
            return r.name

    def get_typeName(self, attr):
        try:
            r = AllinpayWorkitenTypes.objects.get(id=attr.types)
        except BaseException as err:
            return ""
        else:
            return r.name

    def get_pidName(self, attr):
        try:
            r = AllinpayPlaceList.objects.get(id=attr.pid)
        except BaseException as err:
            return ""
        else:
            return r.basename

    def get_rawardName(self, attr):
        try:
            r = AllinpayRawardList.objects.filter(
                id__in=list(eval(attr.raward))
            ).values("id", "name")
        except BaseException as err:
            return []
        else:
            return list(r)

    def get_cameraName(self, attr):
        """摄像头"""
        try:
            r = AllinpayPlacecameraList.objects.filter(
                id__in=list(eval(attr.camera))
            ).values("id", "name")
        except BaseException as err:
            return []
        else:
            return list(r)

    def get_staffName(self, attr):
        """员工"""
        try:
            r = AllinpayStaffList.objects.get(id=attr.onstaff)
        except BaseException as err:
            return ""
        else:
            return r.basename

    def get_submitObj(self, attr):
        """提交记录"""
        try:
            r = AllinpayPlaceworkitemSubmit.objects.get(wid=attr.id)
        except BaseException as err:
            return {}
        else:
            return AllinpayPlaceworkitemSubmitSerializer(r).data

    def get_checkObj(self, attr):
        """点检记录"""
        try:
            r = AllinpayPlaceworkitemCheck.objects.get(wid=attr.id)
        except BaseException as err:
            return {}
        else:
            return AllinpayPlaceworkitemCheckSerializer(r).data

    def validate_types(self, attr):
        if not attr in list(
            AllinpayWorkitenTypes.objects.all().values_list("id", flat=True)
        ):
            raise serializers.ValidationError("作业类型")
        return attr

    def validate_pid(self, attr):
        if not attr in list(
            AllinpayPlaceList.objects.all().values_list("id", flat=True)
        ):
            raise serializers.ValidationError("场所ID错误")
        return attr

    def validate_onstaff(self, attr):
        if not attr in list(
            AllinpayPlacestaffList.objects.all().values_list("sid", flat=True)
        ):
            raise serializers.ValidationError("场所绑定员工ID错误")
        return attr

    # def validate_outtype(self, attr):
    #     if not attr in list(
    #         AllinpayIntegralList.objects.all().values_list("id", flat=True)
    #     ):
    #         raise serializers.ValidationError("分值类型ID错误")
    #     return attr

    # def validate_subtype(self, attr):
    #     if not attr in list(
    #         AllinpayIntegralList.objects.all().values_list("id", flat=True)
    #     ):
    #         raise serializers.ValidationError("分值类型ID错误")
    #     return attr

    def validate_len0(self, attr):
        if not attr in list(
            AllinpayIntegralList.objects.all().values_list("id", flat=True)
        ):
            raise serializers.ValidationError("分值类型ID错误")
        return attr

    def validate_camera(self, attr):
        x = list(AllinpayPlacecameraList.objects.all().values_list("id", flat=True))
        for i in attr:
            if not int(i) in x:
                raise serializers.ValidationError("camera ID 不合法")
        return attr

    # def validate_raward(self, attr):
    #     x = list(AllinpayRawardList.objects.all().values_list("id", flat=True))
    #     for i in attr:
    #         if not int(i) in x:
    #             raise serializers.ValidationError("raward ID 不合法")
    #     return attr

    def validate(self, attrs):
        sess = attrs.copy()
        # if sess.get("raward"):
        #     """奖励模板"""
        #     a = AllinpayRawardList.objects.filter(
        #         pid=sess.get("pid"), id__in=list(sess["raward"])
        #     )
        #     if len(a) < len(list(sess["raward"])):
        #         raise serializers.ValidationError({"raward": "分值模板错误"})
        if sess.get("onstaff"):
            """员工"""
            try:
                AllinpayPlacestaffList.objects.get(
                    pid=sess.get("pid"), sid=sess["onstaff"], status=1
                )
            except BaseException as err:
                raise serializers.ValidationError({"onstaff": "员工错误"})
        # if sess.get("isout"):
        #     if not sess.get("outtype"):
        #         raise serializers.ValidationError({"outtype": "超时分值类型不能为空"})
        #     try:
        #         a = AllinpayIntegralList.objects.get(id=sess.get("outtype"))
        #     except BaseException as err:
        #         raise serializers.ValidationError({"outtype": "超时分值类型不存在"})
        #     else:
        #         if a.total and sess.get("outinter") < 0:
        #             raise serializers.ValidationError({"outtype": "超时分值类型只能累加"})
        # if sess.get("issub"):
        #     if not sess.get("subtype"):
        #         raise serializers.ValidationError({"subtype": "未提交分值类型不能为空"})
        #     try:
        #         a = AllinpayIntegralList.objects.get(id=sess.get("subtype"))
        #     except BaseException as err:
        #         raise serializers.ValidationError({"subtype": "未提交分值类型不存在"})
        #     else:
        #         if a.total and sess.get("subinter") < 0:
        #             raise serializers.ValidationError({"subtype": "未提交分值类型只能累加"})
        return sess

    def to_representation(self, instance):
        """mysql to python"""
        # print(instance.camera, type(instance.camera))
        ret = super().to_representation(instance)
        if ret.get("raward"):
            ret["raward"] = [
                int(x) for x in list(eval(str(instance.raward))) if type(x) == str
            ]
        if ret.get("camera"):
            ret["camera"] = [
                int(x) for x in list(eval(str(instance.camera))) if type(x) == str
            ]
        return ret


class AllinpayAggregationGradeListSerializer(serializers.Serializer):
    """聚合排班表"""

    pid = IntegerField(help_text="场所ID")
    grade = ListField(allow_null=True, child=IntegerField(), help_text="班次列表")
    staff = ListField(allow_null=True, child=IntegerField(), help_text="员工列表")
    today = ListField(
        child=DateField(),
        help_text="日期列表(起,止)",
    )

    class Meta:
        fields = "__all__"

    def validate_pid(self, attr):
        if not attr in list(
            AllinpayPlaceList.objects.all().values_list("id", flat=True)
        ):
            raise serializers.ValidationError("场所ID错误")
        return attr

    def validate_grade(self, attr):
        x = list(AllinpayPlaceGrade.objects.values_list("id", flat=True))
        for i in attr:
            if not i in x:
                raise serializers.ValidationError("grade ID 无效")
        return attr

    def validate_staff(self, attr):
        x = list(AllinpayStaffList.objects.values_list("id", flat=True))
        for i in attr:
            if not i in x:
                raise serializers.ValidationError("staff ID 无效")
        return attr


class AllinpayWorkitenTypesSerializer(serializers.ModelSerializer):
    """工作项类型"""

    id = IntegerField(label="ID", read_only=True)
    name = CharField(allow_blank=True, allow_null=True, help_text="工作项类型名称")

    class Meta:
        model = AllinpayWorkitenTypes
        fields = "__all__"


# class AllinpayWorkitemSubmitSerializer(serializers.ModelSerializer):
#     id = IntegerField(label="ID", read_only=True)

#     class Meta:
#         model = AllinpayPlaceworkitemList
#         fields = "__all__"


class AllinpayPlaceworkitemSubmitSerializer(serializers.ModelSerializer):
    """工作项事务提交"""

    id = IntegerField(label="ID", read_only=True)
    wid = IntegerField(
        validators=[
            UniqueValidator(queryset=AllinpayPlaceworkitemSubmit.objects.all())
        ],
        help_text="工作项事务ID",
    )
    sid = IntegerField(help_text="员工真实ID")
    pics = ListField(child=CharField(), help_text="照片列表")
    currentime = DateTimeField(read_only=True, default=timezone.now, help_text="提交时间")
    notes = CharField(
        allow_blank=True, allow_null=True, required=False, help_text="备注信息"
    )

    class Meta:
        model = AllinpayPlaceworkitemSubmit
        fields = "__all__"
        validators = [
            UniqueTogetherValidator(
                queryset=AllinpayPlaceworkitemSubmit.objects.all(),
                fields=("wid", "sid"),
            )
        ]

    def validate_wid(self, attr):
        if not attr in list(
            AllinpayPlaceworkitemList.objects.filter(
                status=1, currentdate=date.today()
            ).values_list("id", flat=True)
        ):
            raise serializers.ValidationError({"workitemlist.id": "只能当天提交"})
        return attr

    def validate(self, attrs):
        try:
            w = AllinpayPlaceworkitemList.objects.get(id=attrs["wid"], status=1)
        except BaseException as err:
            raise serializers.ValidationError({"workitemlist.id": "工作项错误"})
        if not w.onstaff == attrs["sid"]:
            raise serializers.ValidationError({"workitemlist.onstaff": "只能本人提交"})
        return attrs

    def to_representation(self, instance):
        """mysql to python"""
        ret = super().to_representation(instance)
        if ret.get("pics"):
            ret["pics"] = [x for x in list(eval(str(instance.pics))) if type(x) == str]
        return ret


class AllinpayPlaceworkitemCheckSerializer(serializers.ModelSerializer):
    """工作项事务点检"""

    id = IntegerField(label="ID", read_only=True)
    wid = IntegerField(
        validators=[UniqueValidator(queryset=AllinpayPlaceworkitemCheck.objects.all())],
        help_text="工作项事务ID",
    )
    sid = IntegerField(help_text="员工真实ID")
    intertype = IntegerField(required=False, help_text="积分类型ID")
    raward = IntegerField(default=0, help_text="考核积分(字段值)")
    level = CharField(allow_blank=True, allow_null=True, help_text="考核等级(字段名)")
    currentime = DateTimeField(read_only=True, default=timezone.now, help_text="提交时间")
    notes = CharField(
        allow_blank=True, allow_null=True, required=False, help_text="备注信息"
    )

    staffName = SerializerMethodField()
    rawardName = SerializerMethodField()

    class Meta:
        model = AllinpayPlaceworkitemCheck
        fields = "__all__"

    def validate_wid(self, attr):
        try:
            AllinpayPlaceworkitemSubmit.objects.get(wid=attr)
        except BaseException as err:
            raise serializers.ValidationError("对象未提交,不能点检")
        return attr

    def validate(self, attrs):
        try:
            w = AllinpayPlaceworkitemList.objects.get(id=attrs["wid"], status=1)
            sw = AllinpayPlaceworkitemListSerializer(w).data
        except BaseException as err:
            raise serializers.ValidationError({"workitemlist.id": "工作项错误"})
        # if not str(attrs["raward"]) in list(eval(str(w.raward))):
        #     raise serializers.ValidationError({"workitemlist.raward": "奖励模板超出范围"})
        # if sw.get(attrs["raward"] is None):
        #     raise serializers.ValidationError({"workitemlist.raward": "奖励分值不能为空"})
        if not attrs["sid"] in list(
            AllinpayPlacestaffList.objects.filter(pid=w.pid).values_list(
                "sid", flat=True
            )
        ):
            raise serializers.ValidationError({"workitemlist.sid": "员工非法"})
        if attrs["sid"] == w.onstaff:
            raise serializers.ValidationError({"workitemlist.sid": "不能点检自己"})
        # attrs["raward"] = sw.get(attrs["raward"])
        # attrs["notes"] = sw.get("len0")
        return attrs

    def get_staffName(self, attr):
        try:
            s = AllinpayStaffList.objects.get(id=attr.sid)
        except BaseException as err:
            return ""
        else:
            return s.basename

    def get_rawardName(self, attr):
        try:
            r = AllinpayIntegralList.objects.get(id=attr.intertype)
            # r = AllinpayRawardList.objects.get(id=attr.raward)
        except BaseException as err:
            return ""
        else:
            return r.name


class AllinpayPlaceinterConferializer(serializers.ModelSerializer):
    """积分兑换配置"""

    id = IntegerField(label="ID", read_only=True)
    pid = IntegerField(help_text="场所ID")
    intetype = IntegerField(help_text="积分类型ID")
    scale = IntegerField(help_text="兑换比例(每1个积分能兑换的RMB分)")
    rate = ChoiceField(
        choices=[(i["id"], i["name"]) for i in settings.ALL_INTER_CONF],
        help_text="兑换频率(1次)[1,2,3,4]",
    )
    mixamount = IntegerField(
        help_text="最小兑换积分",
    )
    isauto = IntegerField(
        max_value=1,
        min_value=0,
        default=0,
        help_text="自动兑换",
    )
    currentime = DateTimeField(read_only=True, help_text="修改时间")

    pidName = SerializerMethodField()
    inteName = SerializerMethodField()
    rateName = SerializerMethodField()

    class Meta:
        model = AllinpayPlaceinterConf
        fields = "__all__"
        validators = [
            UniqueTogetherValidator(
                queryset=AllinpayPlaceinterConf.objects.all(),
                fields=("pid", "intetype"),
            )
        ]

    def get_pidName(self, attr):
        try:
            r = AllinpayPlaceList.objects.get(id=attr.pid)
        except BaseException as err:
            return ""
        else:
            return r.basename

    def get_inteName(self, attr):
        try:
            r = AllinpayIntegralList.objects.get(id=attr.intetype)
        except BaseException as err:
            return ""
        else:
            return r.name

    def get_rateName(self, attr):
        try:
            from bisect import bisect_left

            ages = [p["id"] for p in settings.ALL_INTER_CONF]
            index = bisect_left(ages, attr.rate)
            if index != len(ages) and ages[index] == attr.rate:
                return settings.ALL_INTER_CONF[index]["name"]
        except BaseException as err:
            return ""
        else:
            return ""

    def validate_pid(self, attr):
        try:
            r = AllinpayPlaceList.objects.get(id=attr, status=1)
        except BaseException as err:
            raise serializers.ValidationError("场所不存在或未启用")
        else:
            return r.id

    def validate_intetype(self, attr):
        try:
            r = AllinpayIntegralList.objects.get(id=attr, status=1)
        except BaseException as err:
            raise serializers.ValidationError("员工积分类型不存在或未启用")
        else:
            return r.id

    # def validate(self, attrs):
    #     if attrs["mixamount"] < attrs["scale"]:
    #         raise serializers.ValidationError("最小兑换分值不能低于兑换比例")
    #     return attrs


class AllinpayPlaceRangeSerializer(serializers.ModelSerializer):
    """场所编码转换"""

    id = IntegerField(label="ID", read_only=True)
    barcode = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=True,
        validators=[UniqueValidator(queryset=AllinpayPlaceRange.objects.all())],
    )
    bartype = ChoiceField(
        choices=[i for i in settings.ALL_CODE_RANGE],
        help_text="编码类型",
    )
    pid = IntegerField(allow_null=True, required=True)

    class Meta:
        model = AllinpayPlaceRange
        fields = "__all__"
        validators = [
            UniqueTogetherValidator(
                queryset=AllinpayPlaceRange.objects.all(), fields=("barcode", "bartype")
            )
        ]


class AllinpayPlacedeatLogsSerializer(serializers.ModelSerializer):
    """无序列化"""

    id = IntegerField(label="ID", read_only=True)
    pid = IntegerField(allow_null=True, required=False)
    deatdate = DateField(allow_null=True, required=False)
    answer = IntegerField(read_only=True, help_text="操作员")
    creatime = DateTimeField(read_only=True, help_text="创建时间")
    status = IntegerField(read_only=True, help_text="状态")
    super = IntegerField(read_only=True, help_text="审核员")
    lastime = DateTimeField(read_only=True, help_text="审核时间")

    class Meta:
        model = AllinpayPlacedeatLogs
        fields = "__all__"

    def create(self, validated_data):
        if not validated_data.get("deatdate"):
            raise serializers.ValidationError({"deatdate": "缺少有效期"})
        if not validated_data.get("pid"):
            raise serializers.ValidationError({"pid": "缺少场所ID"})
        return AllinpayPlacedeatLogs.objects.create(**validated_data)

    def validate_pid(self, attr):
        try:
            AllinpayPlaceList.objects.get(id=attr)
        except BaseException as err:
            raise serializers.ValidationError("场所对象不存在")
        return attr


class AllinpayPlacedeatListSerializer(serializers.ModelSerializer):
    """无序列化"""

    class Meta:
        model = AllinpayPlacedeatList
        fields = "__all__"


# print(repr(AllinpayPlacedeatLogsSerializer()))
